package com.mht.book.operation.impl;

import com.mht.book.entity.book.Book;
import com.mht.book.entity.book.BookList;
import com.mht.book.operation.Operations;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangfusheng
 * @version 1.0.0
 * @ClassName SaveOperation.java
 * @Description 将书架中的书籍存储到本地文件中
 * @createTime 2022/12/412:13
 */
public class SaveOperation implements Operations{
    @Override
    public void work(BookList bookList) {
        System.out.println("数据将存储到: books.txt 存储中");
        //利用ObjectOutputStream创建序列化流对象，并将序列化后的集合数据存储到books.txt中
        //创建的序列化的流对象
        ObjectOutputStream oos = null;
        try {
            List<Book> list = new ArrayList<>();
            for (int i = 0; i < bookList.getUsedSize(); i++) {
                list.add(bookList.getBook(i));
            }
            //序列化：list集合转换为ObjectOutputStream
            oos = new ObjectOutputStream(new
                    FileOutputStream("books.txt"));
            oos.writeObject(list);
//            oos.writeObject(bookList.getBooks());
            oos.flush();
            oos.close();
            System.out.println("数据已存储到books.txt中");
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                oos.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

//    public static void main(String[] args) {
//        SaveOperation save = new SaveOperation();
//        save.work(new BookList());
//    }
}
